package com.situ.mall.controller.back;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.situ.mall.common.ServerResponse;

@Controller
@RequestMapping("/upload")
public class UploadController {

	@RequestMapping("/uploadImge")
	@ResponseBody
	public ServerResponse uploadImge(MultipartFile file) {
		// 为了防止文件重名（重名的文件会被覆盖丢失），所以要生成一个不重复的随机的名字
		String name = UUID.randomUUID().toString().replace("-", "");
		// 获得后缀.jpg   .png
		System.out.println(file.getOriginalFilename());
		String extension = FilenameUtils.getExtension(file.getOriginalFilename());
		String fileName = name + "." + extension;
		// d:/pic/.....
		String filePath = "D:\\pic\\" + fileName;
		try {
			file.transferTo(new File(filePath));
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		// fileName文件的名字是要存储到数据库里面，所以要告诉前台，插入到前台的form表单里面
		// 执行insert的时候product对象的属性mainImage才有值
		return ServerResponse.createSuccess("上传成功", fileName);
	}
}
